package com.tonicgb.shared.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zhaiyujin
 * @date 2021-09-07 14:55:26
 * @说明 定时器添加线程池,防止任务阻塞
 */
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
    private final int poolSize = 30;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        //简单粗暴的方式直接指定
        //scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
        //也可以自定义的线程池，方便线程的使用与维护，这里不多说了
        scheduledTaskRegistrar.setTaskScheduler(getMyThreadPoolTaskScheduler());
    }



    public TaskScheduler getMyThreadPoolTaskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(poolSize);
        taskScheduler.setThreadNamePrefix("TonicGB-Scheduled-");
        taskScheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //调度器shutdown被调用时等待当前被调度的任务完成
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        //等待时长
        taskScheduler.setAwaitTerminationSeconds(60);
        return taskScheduler;
    }
}
